<template>
  <div>
    <el-form label-width="80px" :inline="true">
      <el-form-item label="学生姓名">
        <el-input
          v-model="search.name"
          placeholder="请输入学生姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input
          v-model="search.phone"
          placeholder="请输入联系方式"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="所属地区">
        <el-cascader
          v-model="search.area"
          :options="$store.state.common.regions"
          :props="{ checkStrictly: true }"
          placeholder="请选择所属地区"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="线下学校">
        <el-select
          v-model="search.school"
          filterable
          remote
          reserve-keyword
          placeholder="请选择线下学校"
          :remote-method="getOfflineSchool"
          :loading="loading"
          clearable
        >
          <el-option
            v-for="item in offlineSchool"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生命周期">
        <nice-select
          v-model="search.life_cycle"
          placeholder="请选择生命周期"
          clearable
          :options="statusArr.life_cycle"
        ></nice-select>
      </el-form-item>
      <el-form-item label="购买次数">
        <nice-select
          v-model="search.consume_time"
          placeholder="请选择购买次数"
          clearable
          :options="statusArr.consume"
        ></nice-select>
      </el-form-item>
      <el-form-item label="回访状态">
        <nice-select
          v-model="search.return_visit"
          placeholder="请选择回访状态"
          clearable
          :options="statusArr.return_visit"
        ></nice-select>
      </el-form-item>
      <el-form-item label="续费状态">
        <nice-select
          v-model="search.renew"
          placeholder="请选择续费状态"
          clearable
          :options="statusArr.renew"
        ></nice-select>
      </el-form-item>
      <el-form-item label="退费状态">
        <nice-select
          v-model="search.refund"
          placeholder="请选择退费状态"
          clearable
          :options="statusArr.refund"
        ></nice-select>
      </el-form-item>
      <el-form-item label="付费状态">
        <nice-select
          v-model="search.payment"
          placeholder="请选择付费状态"
          clearable
          :options="statusArr.payment"
        ></nice-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" size="small"
          >搜索</el-button
        >
      </el-form-item>
      <div class="right">
        <el-form-item class="right">
          <div class="u-btn-box">
            <el-button type="primary" @click="dataExportHandle" size="small"
              >数据导出</el-button
            >
            <el-button type="primary" @click="downHandle" size="small"
              >模板下载</el-button
            >
            <div class="margin-left10 margin-right10">
              <el-upload
                ref="uploadExl"
                action
                multiple
                :limit="1"
                :http-request="importObj"
                :before-upload="beforeUploadImg"
                :show-file-list="false"
              >
                <el-button type="primary" class="u-btn">批量导入</el-button>
              </el-upload>
            </div>
            <el-button type="primary" @click="addHandle" size="small"
              >新增学生</el-button
            >
          </div>
        </el-form-item>
      </div>
    </el-form>
    <nice-table
      :data="list"
      :showIndex="true"
      :columns="columns"
      :pagination="pagination"
    >
      <el-table-column
        label="操作"
        align="center"
        width="100"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="applyHandle(scope.row)"
            >报名</el-button
          >
          <el-button
            size="small"
            type="text"
            @click="deleteHandle(scope.row)"
            disabled
            >删除</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <!-- 弹窗, 新增学生  -->
    <add-student
      v-if="addDialogVisible"
      ref="addDialog"
      @refreshDataList="getDataList"
      :source="selectArr.source"
    ></add-student>
    <batch-apply
      v-if="applyVisible"
      ref="applyForm"
      @refreshDataList="getDataList"
      :applyWay="applyWay"
      :multipleSelection="multipleSelection"
    ></batch-apply>
  </div>
</template>
<script>
import base from "@/views/base.vue";
import AddStudent from "./add-student";
import AdjustDate from "./adjust-date";
import BatchApply from "../school-list/batch-apply";
import {
  queyEnumByTableName,
  cascadeQuery,
  downloadTemplateFile,
  importData
} from "@/api/api.js";
import {
  queryPageList,
  deleteStudent,
  exportDataAsync,
  exportQueryList
} from "@/api/user.js";
export default {
  name: "students-administration",
  extends: base,
  components: {
    AddStudent,
    AdjustDate,
    BatchApply
  },
  data() {
    return {
      search: {
        phone: "",
        name: "",
        area: [],
        school: "",
        life_cycle: "",
        consume_time: "",
        return_visit: "",
        renew: "",
        refund: "",
        payment: ""
      },
      url: "",
      exportloading: {},
      multipleSelection: [],
      selectArr: {
        status: [], // 状态
        source: [] // 学生来源
      },
      statusArr: {
        life_cycle: [], // 生命周期
        consume: [], // 购买次数
        return_visit: [], // 回访状态
        renew: [], // 续费状态
        refund: [], // 退费状态
        payment: [] // 付费状态
      },
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCurrentChange,
        handleSizeChange: this.handleSizeChange
      },
      offlineSchool: [],
      loading: false,
      export_id: 0,
      list: [],
      timer: null,
      applyVisible: false,
      applyWay: "",
      columns: [
        {
          label: "姓名",
          prop: "name",
          extends: [
            {
              clickFunction: val => {
                this.viewDetail(val);
              }
            }
          ]
        },
        {
          label: "联系方式",
          prop: "phone",
          width: 150,
          extends: [
            {
              clickFunction: val => {
                this.viewPhone(val);
              },
              goFunction: val => {
                this.viewDetail(val);
              },
              isView: true
            }
          ]
        },
        {
          label: "性别",
          prop: "sex",
          extends: [
            {
              filterFunction: val => {
                return this.$filterSex(val);
              }
            }
          ]
        },
        {
          label: "线下学校",
          prop: "school_name"
        },
        {
          label: "线下班级",
          prop: "school_class_name"
        },
        {
          label: "邮寄地址",
          prop: "address"
        },
        {
          label: "来源",
          prop: "source",
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(val, this.selectArr.source);
              }
            }
          ]
        }
      ],
      addDialogVisible: false
    };
  },
  activated() {
    this.$store.dispatch("common/saveRegion");
    this.url = this.$http.adornUrl(
      `/questionlib/sys/oss/upload?token=${this.$cookie.get("token")}`
    );
    this.getDataList();
    this.queyEnumByTableName();
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    async getDataList() {
      let school = "";
      if (this.offlineSchool && this.offlineSchool.length) {
        this.offlineSchool.forEach(ele => {
          if (ele.value === this.search.school) {
            school = ele.label;
          }
        });
      }
      let res = await cascadeQuery({
        table_name: "nice_student",
        condition: {
          "user_base.real_name": [{ like: this.search.name }],
          "school.province": this.search.area[0],
          "school.city": this.search.area[1] || "",
          "school.area": this.search.area[2] || "",
          "school.school_name": school,
          "user_base.mobile": [{ like: this.search.phone }], // 联系方式
          "status.life_cycle": this.search.life_cycle,
          "status.consume_time": this.search.consume_time,
          "status.return_visit": this.search.return_visit,
          "status.renew": this.search.renew,
          "status.refund": this.search.refund,
          "status.payment": this.search.payment
        },
        by_order: "create_time desc",
        member:
          "teacher_name,school_name,sex,phone,name,birth_date,class_name,head_url,school_class_name,contacts,address,account,life_cycle,consume_time,return_visit,renew,refund,payment",
        by_page: {
          currPage: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (data.data) {
          this.pagination.total = data.data.totalCount;
          this.list = data.data.list;
          if (this.list && this.list.length) {
            this.list.forEach(ele => {
              ele.isView = false;
            });
          }
        }
      }
    },
    applyHandle(row) {
      this.applyVisible = true;
      this.applyWay = "single";
      this.$nextTick(() => {
        this.$refs.applyForm.init(row.user_id);
      });
    },
    async queyEnumByTableName() {
      let res = await queyEnumByTableName({ tableName: "nice_student" });
      if (res[0]) {
        return;
      }
      let arr = res[1].data;
      Object.keys(this.selectArr).forEach(item => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].fieldName === item) {
            this.selectArr[item] = arr[i].child;
          }
        }
      });
      Object.keys(this.statusArr).forEach(item => {
        this.selectArr.status
          .filter(ele => {
            return ele.child && ele.child.length;
          })
          .forEach(ele => {
            if (ele.real_value === item) {
              this.statusArr[item] = ele.child;
            }
          });
      });
      this.statusArr = this.parseFilter(this.statusArr);
      this.selectArr = this.parseFilter(this.selectArr);
    },
    parseFilter(arr) {
      return JSON.parse(
        JSON.stringify(arr)
          .split("display_value")
          .join("label")
          .split("child")
          .join("children")
          .split("t_id")
          .join("value")
      );
    },
    // 批量导入
    async importObj(e) {
      let formData = new FormData();
      formData.append("file", e.file);
      let res = await importData(formData);
      if (res[0]) {
        return;
      }
      this.getDataList();
      this.$ref.uploadExl.clearFiles();
    },
    // 上传封面前验证
    beforeUploadImg(file) {
      const isExcel =
        file.type === "application/vnd.ms-excel" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isLt100M = file.size / 1024 / 1024 < 200;

      if (!isExcel) {
        this.$message.error("上传的文件只能是 xls 或 xlsx 格式!");
      }
      if (!isLt100M) {
        this.$message.error("上传的文件大小不能超过 200MB!");
      }
      return isExcel && isLt100M;
    },
    async dataExportHandle() {
      let res = await exportDataAsync({
        table_name: "nice_student",
        "result_field,create_time": "source",
        condition: [],
        by_order: "create_time desc",
        member: "name,phone,sex,school_name,class_name,address,contacts",
        by_page: { currPage: 1, pageSize: 1000 },
        data: [
          { header: "姓名", tableandfield: "name" },
          { header: "联系方式", tableandfield: "phone" },
          { header: "性别", tableandfield: "sex" },
          { header: "线下学校", tableandfield: "school_name" },
          { header: "线下班级", tableandfield: "class_name" },
          { header: "邮寄地址", tableandfield: "address" },
          { header: "来源", tableandfield: "source" }
        ]
      });
      console.log("res===>", res);
      if (res[0]) {
        return;
      }
      if (res[1].code === 0) {
        this.exportloading = this.$loading({
          lock: true,
          text: "正在导出中！",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        this.export_id = res[1].data.id;
        this.timer = setInterval(this.exportQueryList, 3000);
      }
    },
    async exportQueryList() {
      let res = await exportQueryList({
        "nice_excel_export_record.id": this.export_id
      });
      if (res[0]) {
        return;
      }
      if (res[1].code === 0) {
        let status = res[1].data.pageList.list[0].status;
        if (status) {
          if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
          }
          let filename = decodeURI("学生列表导出.xlsx");
          this.exportloading.close();
          const anchor = document.createElement("a");
          anchor.href = res[1].data.pageList.list[0].url;
          anchor.download = decodeURI(filename);
          document.body.appendChild(anchor);
          anchor.click();
        }
      }
    },
    async getOfflineSchool(query) {
      if (query !== "") {
        this.loading = true;
        let form = {
          table_name: "nice_school",
          "nice_school.school_name": query
        };
        let res = await queryPageList(form);
        if (res[0]) {
          return;
        }
        let data = res[1];
        this.loading = false;
        if (data && data.code === 0) {
          if (data.data.pageList.list && data.data.pageList.list.length) {
            this.offlineSchool = data.data.pageList.list.map(item => {
              return {
                label: item.school_name,
                value: item.id
              };
            });
          } else {
            this.offlineSchool = [];
          }
        }
      }
    },
    async downHandle() {
      let res = await downloadTemplateFile({
        data: [
          {
            header: "姓名(必填)",
            tableandfield: "sys_user.sys_user_nice_user_base.real_name"
          },
          {
            header: "用户类型(必填)",
            tableandfield:
              "sys_user.user_type:sys_user.sys_user_nice_user_base.user_type"
          },
          { header: "账号(必填)", tableandfield: "sys_user.username" },
          {
            header: "联系方式(必填)",
            tableandfield:
              "sys_user.sys_user_nice_user_base.mobile:sys_user.sys_user_student_contacts.contacts_mobile"
          },
          {
            header: "联系人",
            tableandfield: "sys_user.sys_user_student_contacts.contacts"
          },
          {
            header: "生日(格式:2020-04-01)",
            tableandfield: "sys_user.sys_user_nice_user_base.birth_date"
          },
          {
            header: "性别(0:男1:女)",
            tableandfield: "sys_user.sys_user_nice_user_base.sex"
          },
          {
            header: "线下学校",
            tableandfield: "sys_user.sys_user_nice_student.school_id"
          },
          {
            header: "线下班级",
            tableandfield: "sys_user.sys_user_nice_student.class_id"
          },
          {
            header: "邮寄地址",
            tableandfield: "sys_user.sys_user_nice_user_base.address"
          }
        ]
      });
      if (res.status === 200) {
        let filename = decodeURI("学生模板下载.xls");
        filename = filename.replace(/\"/g, "");
        this.$downloadExcel(res.data, filename);
      }
    },
    viewPhone(item) {
      this.list.forEach(ele => {
        if (ele.user_id !== item.user_id) {
          ele.isView = false;
        }
      });
      item.isView = !item.isView;
      this.list = [...this.list];
    },
    onSubmit() {
      this.pagination.pageNum = 1;
      this.getDataList();
    },
    deleteHandle(row) {
      this.$confirm("确定进行删除操作", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteStudent(row);
        })
        .catch(() => {});
    },
    async deleteStudent(row) {
      let res = await deleteStudent([
        {
          table_name: "nice_student",
          where: {
            user_id: [row.user_id]
          }
        }
      ]);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.$message.success("删除成功");
        this.getDataList();
      }
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getDataList();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getDataList();
    },
    addHandle() {
      this.addDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.addDialog.init();
      });
    },
    viewDetail(row) {
      console.log("row", row);
      this.$router.push({
        name: "student-detail",
        params: { id: row.user_id }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.u-btn-box {
  display: flex;
}
.u-btn {
  font-size: 12px;
}
</style>
